package cn.ujn.medicalbackend.controller;


import cn.ujn.medicalbackend.common.BaseResponse;
import cn.ujn.medicalbackend.common.ErrorCode;
import cn.ujn.medicalbackend.common.ResultUtils;
import cn.ujn.medicalbackend.domain.Drug;
import cn.ujn.medicalbackend.dto.DrugQuery;
import cn.ujn.medicalbackend.exception.BusinessException;
import cn.ujn.medicalbackend.request.DrugAddRequest;
import cn.ujn.medicalbackend.request.DrugDeleteRequest;
import cn.ujn.medicalbackend.request.DrugUpdateRequest;
import cn.ujn.medicalbackend.service.DrugService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/drug")
@CrossOrigin(origins = {"http://localhost:9092"})
public class DrugController {
    @Autowired
    private DrugService drugService;


    @GetMapping("/list/page")
    public BaseResponse<Page<Drug>> getDrugListByPage(DrugQuery drugQuery) {
        if (drugQuery== null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Drug drug = new Drug();
        BeanUtils.copyProperties(drugQuery, drug);
        QueryWrapper<Drug> queryWrapper = new QueryWrapper<>(drug);
        Page<Drug> page = new Page<>(drugQuery.getPageNum(), drugQuery.getPageSize());
        Page<Drug> tempPage = drugService.page(page, queryWrapper);
        Page<Drug> resultPage = drugService.DrugPageTransfer(tempPage);
        return ResultUtils.success(resultPage);
    }

    @PostMapping("/add")
    public BaseResponse<Long> addDrug(@RequestBody DrugAddRequest drugAddRequest, HttpServletRequest request) {
        if (drugAddRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        long drugId =drugService.addDrug(drugAddRequest, request);
        return ResultUtils.success(drugId);
    }

    @PostMapping("/update")
    private BaseResponse<Boolean> updateDrug(@RequestBody DrugUpdateRequest drugUpdateRequest, HttpServletRequest request) {

        if (drugUpdateRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        boolean result = drugService.updateDrug(drugUpdateRequest,request);
        return ResultUtils.success(true);
    }

    @PostMapping("/delete")
    private BaseResponse<Boolean> deleteDrug(@RequestBody DrugDeleteRequest drugDeleteRequest, HttpServletRequest request) {
        if (drugDeleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = drugService.deleteDrug(drugDeleteRequest, request);
        return ResultUtils.success(result);
    }

}
